package codeTop;

import java.util.ArrayList;
import java.util.List;

public class q151 {
    public String reverseWords(String s) {
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!sb.isEmpty()&&s.charAt(i) == ' ') {
                list.add(sb.toString());
                sb.delete(0,sb.length());
            }else if (s.charAt(i)!=' '){
                sb.append(s.charAt(i));
            }
        }
        if (!sb.isEmpty()) {
            list.add(sb.toString());
            sb.delete(0,sb.length());
        }
        if (list.isEmpty()) {
            return "";
        }
        for (int i = list.size()-1; i >0 ; i--) {
            sb.append(list.get(i));
            sb.append(" ");
        }
        sb.append(list.get(0));
        return sb.toString();
    }

    public static void main(String[] args) {
        q151 q = new q151();
        System.out.println(q.reverseWords("  hello world  "));
    }
}
